﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace CPPEI.DataAccess
{
    public static class DB
    {
        private static string s_connectString;

        public static void Init(string connectString)
        {
            s_connectString = connectString;
        }

        public static int ExecuteNonQuery(string commandText, SqlParameter[] dbParams)
        {
            using (SqlConnection connection = new SqlConnection(s_connectString))
            {
                connection.Open();

                SqlCommand command = new SqlCommand(commandText, connection);
                command.Parameters.AddRange(dbParams);

                return command.ExecuteNonQuery();
            }
        }

        public static DataSet QueryDataSet(string commandText)
        {
            using (SqlConnection connection = new SqlConnection(s_connectString))
            {
                connection.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(commandText, connection);

                DataSet dataSet = new DataSet();
                adapter.Fill(dataSet);
                return dataSet;
            }
        }

        public static DataSet QueryDataSet(string commandText, SqlParameter[] dbParams)
        {
            using (SqlConnection connection = new SqlConnection(s_connectString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(commandText, connection);
                command.Parameters.AddRange(dbParams);
                SqlDataAdapter adapter = new SqlDataAdapter(command);

                DataSet dataSet = new DataSet();
                adapter.Fill(dataSet);
                return dataSet;
            }
        }

        public static DataTable QueryDataTable(string commandText)
        {
            DataSet dataSet = QueryDataSet(commandText);
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                return dataSet.Tables[0];
            }
            return null;
        }

        public static DataTable QueryDataTable(string commandText, SqlParameter[] dbParams)
        {
            DataSet dataSet = QueryDataSet(commandText, dbParams);
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                return dataSet.Tables[0];
            }
            return null;
        }
    }
}
